package com.example.quarkus.exception;

import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

/**
 * @author: Hu Shan
 * @date: 2023/3/23 19:12
 * @description: 全局统一异常处理
 */
@Provider
public class GlobalExceptionHandler implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable exception) {
        if (exception instanceof BusinessException) {
            BusinessException businessException = (BusinessException) exception;
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorMessage(businessException.getMessage(), false))
                    .type(MediaType.APPLICATION_JSON)
                    .build();
        } else {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(new ErrorMessage(exception.getMessage(), false))
                    .type(MediaType.APPLICATION_JSON)
                    .build();
        }
    }
}
